<?php
declare (strict_types = 1);

namespace app\middleware;

use app\model\User as UserModel;
use think\Response;

class Check
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //过滤登录 注册 获取验证码 请求的拦截
        $path = request()->pathinfo();
        if ($path == "login" ||$path == "registration" ||$path == "get_captcha") {
            return $next($request);
        }
        //获取携带的token
        $token = $request->header('token');
        //未携带token
        if(empty($token)){
            return json(['code' => 551, 'msg' => '请求头错误']);
        }
        //使用携带的token进行信息查询
        $result=UserModel::where('token', $token)->find();

        //查不到信息，登录过期
        if(empty($result)){
            return json(['code' => 552, 'msg' => '登录过期']);
        }else{
            //将用户id和手机号保存
            $request->userId = $result->id;
            $request->tel = $result->tel;
            return $next($request);
        }
    }
}
